package com.mm.fam.web.service.impl;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.mm.fam.common.utils.DockerUtils;
import com.mm.fam.web.base.CommonConstant;
import com.mm.fam.web.base.ResponseModel;
import com.mm.fam.web.base.ResponseUtil;
import com.mm.fam.web.entity.Node;
import com.mm.fam.web.service.ContainerService;
import com.mm.fam.web.service.NodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ContainerServiceImpl implements ContainerService {

    @Value("${docker.ip}")
    private String dockerIp;
    @Value("${docker.image-name}")
    private String imageName;

    @Autowired
    private NodeService nodeService;


    @Override
    public ResponseEntity<ResponseModel<Object>> startContainer(int nodeId) {
        ResponseEntity<ResponseModel<Object>> res = null;
        try {
            Node node = nodeService.getNodeById(nodeId);
            if(node != null){
                if(node.getToken() != null && !"".equals(node.getToken()) ){
                    List<String> envs = new ArrayList<>();
                    envs.add("nodeId=" + nodeId);
                    envs.add("token=" + node.getToken());
                    DockerClient client = DockerUtils.client(dockerIp);
                    CreateContainerResponse container = DockerUtils.startContainer(client, envs, Integer.toString(nodeId), imageName);
                    log.info("----------------------容器id："+container.getId());
                    //更新网关容器id 状态
                    nodeService.updateContainer(nodeId,container.getId(),CommonConstant.ContainerStatus.STATUS_START);
                    res = ResponseUtil.success(CommonConstant.Message.OPTION_SUCCESS);
                }else{
                    res = ResponseUtil.fail("token 为空");
                }

            }
        } catch (NotFoundException e) {
            res = ResponseUtil.fail("未找到此镜像");
        } catch (Exception e) {
            e.printStackTrace();
            res = ResponseUtil.fail("启动失败");
        }
        return res;
    }

    @Override
    public ResponseEntity<ResponseModel<Object>> stopContainer(int nodeId) {
        ResponseEntity<ResponseModel<Object>> res = null;
        try {
            Node node = nodeService.getNodeById(nodeId);
            if(node != null && node.getContainerId() != null && !"".equals(node.getContainerId())){
                DockerClient client = DockerUtils.client(dockerIp);
                boolean result = DockerUtils.stopContainer(client,node.getContainerId());
                if(result){
                    //更新网关容器id 状态
                    nodeService.updateContainer(nodeId,null,CommonConstant.ContainerStatus.STATUS_STOP);
                }

                res = ResponseUtil.success(CommonConstant.Message.OPTION_SUCCESS);
            }else{
                res = ResponseUtil.fail("未找到此容器");
            }
        } catch (NotFoundException e) {
            res = ResponseUtil.fail("未找到此镜像");
        } catch (Exception e) {
            e.printStackTrace();
            res = ResponseUtil.fail("停止容器失败");
        }
        return res;
    }

    @Override
    public ResponseEntity<ResponseModel<Object>> restartContainer(int nodeId) {
        ResponseEntity<ResponseModel<Object>> res = null;
        try {
            Node node = nodeService.getNodeById(nodeId);
            if(node != null && node.getContainerId() != null && !"".equals(node.getContainerId())){
                DockerClient client = DockerUtils.client(dockerIp);
                boolean result = DockerUtils.stopContainer(client,node.getContainerId());
                if(result){
                    if(node.getToken() != null && !"".equals(node.getToken()) ){
                        //更新网关容器id 状态
                        List<String> envs = new ArrayList<>();
                        envs.add("nodeId=" + nodeId);
                        envs.add("token=" + node.getToken());
                        CreateContainerResponse container = DockerUtils.startContainer(client, envs, Integer.toString(nodeId), imageName);
                        log.info("----------------------容器id："+container.getId());
                        //更新网关容器id 状态
                        nodeService.updateContainer(nodeId,container.getId(),CommonConstant.ContainerStatus.STATUS_START);
                        res = ResponseUtil.success(CommonConstant.Message.OPTION_SUCCESS);
                    }else{
                        nodeService.updateContainer(nodeId,null,CommonConstant.ContainerStatus.STATUS_STOP);
                        res = ResponseUtil.fail("重启失败，token温控");
                    }

                }
            }else{
                res = ResponseUtil.fail("未找到此容器");
            }
        } catch (NotFoundException e) {
            res = ResponseUtil.fail("未找到此镜像");
        } catch (Exception e) {
            e.printStackTrace();
            res = ResponseUtil.fail("停止容器失败");
        }
        return res;
    }


}
